/*********************************************************************************
 *      Copyright:  (C) 2023 Xie Mujie<1289180278@qq.com> Zhu Lijun<3262465970@qq.com>
 *                  All rights reserved.
 *
 *       Filename:  my_mqtt.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(2023年07月24日)
 *         Author:  Xie Mujie <1289180278@qq.com> Zhu Lijun <3262465970@qq.com>
 *      ChangeLog:  1, Release initial version on "2023年07月24日 10时46分39秒"
 *                 
 ********************************************************************************/
#include "main.h"

static struct mosquitto   *mosq;

struct mosquitto *mqtt_init(mqtt_conf_t *conn_par)
{
	struct mosquitto   *mosq;
	int session = true;
	
	if (!conn_par->clientid || !conn_par->username || !conn_par->passwd)
	{
		log_warn("clientid is null");
		return NULL;
	}

	mosquitto_lib_init();

	mosq = mosquitto_new(conn_par->clientid, session, NULL);
	
	if (mosquitto_username_pw_set(mosq, conn_par->username, conn_par->passwd) != MOSQ_ERR_SUCCESS)
	{
		log_error("connect server failure: %s", strerror(errno));
		return NULL;
	}
	
	return mosq;
}

int mqtt_connect(struct mosquitto *mosq, mqtt_conf_t *conn_par)
{
	if (!mosq || !conn_par->hostname)
	{
		log_warn("mosq or hostname/port/keepalive is null");
		return -1;
	}

	if (mosquitto_connect(mosq, conn_par->hostname, conn_par->port, conn_par->keepalive) != MOSQ_ERR_SUCCESS)
	{
		log_error("connect server failure: %s", strerror(errno));
		return -2;
	}

	if (mosquitto_loop_start(mosq) != MOSQ_ERR_SUCCESS)
	{
		log_error("mosquitto_loop_start_failure: %s", strerror(errno));
		return -3;
	}

	return 0;
}

void mqtt_clean(struct mosquitto *mosq)
{
	mosquitto_destroy(mosq);
	mosquitto_lib_cleanup;
}
